package com.itheima.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.log4j.Log4j2;

import java.util.Calendar;
import java.util.Map;

@Log4j2
public class JwtUtils {
    //鉴权 相当于私钥保存在服务器上
    private static final String secret = "###$$$$%%%%";

    /**
     * 生成token
     *
     * @param map
     * @return
     */
    public static String getToken(Map<String, String> map) {
        //默认七天过期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR, 10);
        //创建JWT
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        //指定令牌过期时间
        builder.withExpiresAt(instance.getTime());
        String token = builder.sign(Algorithm.HMAC256(secret));
        return token;
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token) {
        try {
            return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            log.error("无效签名！");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            log.error("token过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            log.error("算法不一致");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("token无效！");
        }
        return null;
    }


}
